-- Winter Anathema (c) v.v.balashoff
local Domain = require('leviathan/ECS/Domain')
local Entity = require('leviathan/ECS/Entity')
local Log = require('leviathan/Log')
local MusicSystem = require('leviathan/ECS/Audio/Systems/MusicSystem')
local MusicComponent = require('leviathan/ECS/Audio/Components/MusicComponent')
local SoundComponent = require('leviathan/ECS/Audio/Components/SoundComponent')

local DomainAudio = Domain:derive('Audio')

function DomainAudio:new(world)
    -- call parent constructor
    DomainAudio.super.new(self, world, 'Audio')
    -- systems
    local music = MusicSystem(self)
    DomainAudio:addSystem(self, music)
end

function DomainAudio:playMusic(track)
    if not Config.PlayMusic then
        return
    end
    if not track then
        Log:error('[Audio] Cannot find music: '..tostring(track))
        os.exit()
    end
    local e = self:getEntity(track)
    -- loading track to play only if it is new one
    if e then
        -- check if is played
        print('QQQ Audio TODO!')
    else
        -- creating new entity with music component
        Log:warning('[Audio] Addind music: '..tostring(track))
        local musicPlayer = Entity(self, track)
        local musicComp = MusicComponent(track)
        musicPlayer:addComponent(musicComp)
        musicComp.audio:play()
    end
end

function DomainAudio:playSound(track)
    if not Config.PlaySounds then
        return
    end
    -- creating new entity with sound component
    Log:warning('[Audio] Addind sound: '..tostring(track))
    local soundPlayer = Entity(self, track)
    local soundComp = SoundComponent(track)
    soundPlayer:addComponent(soundComp)
    soundComp.audio:play()
end

function DomainAudio:stopMusic(track)
    if e then
        local e = self:getEntity(track)
        local c = e:getComponent('MusicComponent')
        c.enabled = false
        c.audio:stop()
print('MUSIC: stopped:', track)
    else
        local comps = self.components['Audio']
        if comps then
            for i = 1, #comps do
                local comp = comps[i]
                comp.enabled = false
                comp.audio:stop()
print('MUSIC: stpd:', comp.name)
            end
        end
    end
end

return DomainAudio
